package com.dragon.upms.biz.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.core.constant.CommonConstants;
import com.dragon.upms.api.dto.UserDTO;
import com.dragon.upms.api.dto.UserInfo;
import com.dragon.upms.api.entity.SysUser;
import com.dragon.upms.biz.mapper.SysUserMapper;
import com.dragon.upms.biz.service.SysMenuService;
import com.dragon.upms.biz.service.SysRoleService;
import com.dragon.upms.biz.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dragon.upms.api.entity.SysRole;
import com.dragon.upms.api.entity.SysMenu;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @date: 2024/8/5 23:20
 * @author: ybl
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    private final SysRoleService sysRoleService;

    private final SysMenuService sysMenuService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveUser(UserDTO userDTO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userDTO, sysUser);

        sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
        sysUser.setCreateBy(userDTO.getUsername());
        sysUser.setPassword(ENCODER.encode(userDTO.getPassword()));

        baseMapper.insert(sysUser);

        return Boolean.TRUE;

    }

    @Override
    public UserInfo findUserInfo(SysUser sysUser) {

        UserInfo userInfo = new UserInfo();
        userInfo.setSysUser(sysUser);
        // 设置角色列表 （ID）
        List<Long> roleIds = sysRoleService.findRolesByUserId(sysUser.getUserId())
                .stream()
                .map(SysRole::getRoleId)
                .collect(Collectors.toList());
        userInfo.setRoles(ArrayUtil.toArray(roleIds, Long.class));

        // 设置权限列表（menu.permission）
        Set<String> permissions = new HashSet<>();
        roleIds.forEach(roleId -> {
            List<String> permissionList = sysMenuService.findMenuByRoleId(roleId)
                    .stream()
                    .filter(menu -> StrUtil.isNotEmpty(menu.getPermission()))
                    .map(SysMenu::getPermission)
                    .collect(Collectors.toList());
            permissions.addAll(permissionList);
        });
        userInfo.setPermissions(ArrayUtil.toArray(permissions, String.class));
        return userInfo;
    }
}
